package com.alibaba.serverless;

import com.alibaba.serverless.common.ApiGwRequest;
import com.alibaba.serverless.common.ApiGwResponse;
import com.aliyun.fc.runtime.Context;
import com.aliyun.fc.runtime.FunctionComputeLogger;
import com.aliyun.fc.runtime.FunctionInitializer;
import com.aliyun.fc.runtime.PojoRequestHandler;
import com.aliyuncs.utils.Base64Helper;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.util.UUID;

public class NatEipHandler implements FunctionInitializer, PojoRequestHandler<ApiGwRequest, ApiGwResponse> {

	/*
	 * 云函数初始化
	 * 
	 * @see com.aliyun.fc.runtime.FunctionInitializer#initialize(com.aliyun.fc.
	 * runtime.Context)
	 */
	@Override
	public void initialize(Context context) {
		FunctionComputeLogger logger = context.getLogger();
		logger.debug(String.format("RequestID is %s %n", context.getRequestId()));
	}

	/*
	 * Web云函数处理入口
	 * 
	 * @see com.aliyun.fc.runtime.PojoRequestHandler#handleRequest(java.lang.Object,
	 * com.aliyun.fc.runtime.Context)
	 */
	@Override
	public ApiGwResponse handleRequest(ApiGwRequest request, Context context) {
		FunctionComputeLogger logger = context.getLogger();
		String newUUID = UUID.randomUUID().toString();
		
		// 测试访问外网
		String ipInfo = getHttpPage(logger);

		String bodyContext = "<html>" + "<h1>您好！ 生成了一个UUID:" + newUUID + "</h1><br>" + "<h1> IP地址:" + ipInfo + "</h1>"
				+ "</html>";

		ApiGwResponse response = new ApiGwResponse();
		response.getHeaders().put("responseHeader", "testValue");
		response.getHeaders().put("Content-type", "text/html; charset=utf-8");
		// boolean isBase = request.getIsBase64Encoded();
		boolean isBase = false;
		// 响应内容是JSON，不用编码, 建议和 request内部编码保持一致
		if (isBase) {
			try {
				bodyContext = Base64Helper.encode(bodyContext, "UTF-8");
			} catch (UnsupportedEncodingException e) { // 编码失败，就用原文
				isBase = false;
			}
		}

		logger.info("Response返回:" + bodyContext);

		response.setBody(bodyContext);
		response.setBase64Encoded(isBase);
		response.setStatusCode(200);

		return response;

	}


	/**
	 * 外网访问
	 * 
	 * @param logger
	 * @return
	 */
	private String getHttpPage(FunctionComputeLogger logger) {
		try {
			String url = "https://myip.ipip.net/";
			OkHttpClient client = new OkHttpClient();
			Request request = new Request.Builder().url(url).build();
			Response response = client.newCall(request).execute();
			String ipInfo = response.body().string();
			logger.info("访问workbench-bata内容：" + ipInfo);
			return ipInfo;
		} catch (Exception e) {
			logger.info("发生异常：" + ex2String(e));
			return "获取访问外网失败";
		}
	}

	private String ex2String(Exception t) {
		StringWriter sw = new StringWriter();
		t.printStackTrace(new PrintWriter(sw, true));
		return sw.getBuffer().toString();
	}
}